﻿using System.Windows;
using System.Device.Location;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Xml;
using System.Xml.Serialization;
using System.Net.NetworkInformation;
using System.Text;
using Microsoft.Phone.BackgroundTransfer;
using Microsoft.Phone.Net.NetworkInformation;
using System.Data.Common;


namespace BackgroundTask
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;
        private static IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
        string data="";
       
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background
            
            GeoCoordinateWatcher mywatch = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            mywatch.MovementThreshold = 30;
            mywatch.PositionChanged +=  new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
            mywatch.Start();
           
            
            data = string.Format("UserID={0}&Latitude={1}&Longtitude={2}&Description=dang test background", 2, mywatch.Position.Location.Latitude, mywatch.Position.Location.Longitude);
            Uri uri = new Uri("http://miru.esy.es/Service/radarService/Location.php?" + data);


           // string data = Encoding.UTF8.GetString(byteArray, 0, (int)byteArray.Length);
            WebClient webClient = new WebClient();
           //webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(this.WebClient_UploadStringCompleted);
            webClient.UploadProgressChanged+=(s,args)=>
            {
                ShellToast toast = new ShellToast();
                toast.Content = "TransferProgressChanged";
                toast.Title = "Test Result";
                toast.Show();
            };
            // webClient.Headers["Content-type"] = "application/json";
            webClient.Encoding = Encoding.UTF8;
            webClient.UploadStringAsync(uri, "POST", data);
            


            

            NotifyComplete();
        }
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            
            if (settings.Contains("Login") == true)
            {
                if ((bool)settings["Login"] == true)
                {
                    //if (NetworkInterface.GetIsNetworkAvailable() == true)
                    //{
                    //    string aUrl = "http://168.143.162.116/statuses/home_timeline.xml";
                    //    HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(aUrl);
                    //    request.ContentType = "application/x-www-form-urlencoded";
                    //   // request.Credentials = new NetworkCredential(_username, _password);
                    //    //WebResponse tempResp = request.GetResponse();
                    //    //ThreadState state = new ThreadState();
                    //    request.BeginGetResponse(
                    //    //IAsyncResult result = request.BeginGetResponse(new AsyncCallback(???), ???);
                    //}
                }
            }
        }
        public static User LoadSettings()
        {
            User result = new User();

            using (IsolatedStorageFile File = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (File.FileExists("Userlogin.xml"))
                {
                    using (IsolatedStorageFileStream FileStream = new IsolatedStorageFileStream("Userlogin.xml", System.IO.FileMode.Open, File))
                    {
                        try
                        {
                            // Trong FileStream thực hiện Deserialize
                            XmlSerializer serialize = new XmlSerializer(typeof(User));
                            // Ép kiểu về đúng kiểu ban đầu và Gán lại cho Source 
                            result = (User)serialize.Deserialize(FileStream);

                            return result;
                        }
                        catch (Exception ex)
                        {
                        }
                    };
                };
            }
            return null;
        }
    }
    public class User
    {
        public int UserID;
        public string Username;
        public string Password;
        public string Fullname;
        public int Permission;
        public int Status;
    }
}